Partition array into 3 parts with equal sum

Time: O(N); Space: O(1); easy

Given an array A of integers, return True if and only if we can partition the array into three non-empty parts with equal sums.

Formally, we can partition the array if we can find indexes i + 1 < j with (A[0] + A[1] + … + A[i] == A[i+1] + A[i+2] + … + A[j-1] == A[j] + A[j-1] + … + A[len(A) - 1])

Example 1:

Input: A = [0,2,1,-6,6,-7,9,1,2,0,1]

Output: True

Explanation:

    • 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: A = [0,2,1,-6,6,7,9,-1,2,0,1]

Output: False

Example 3:

Input: A = [3,3,6,5,-2,2,5,1,-9,4]

Output: True

Explanation:

    • 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Notes:

  • 3 <= len(A) <= 50000

  • -10^4 <= A[i] <= 10^4

[1]:
class Solution1(object):
    def canThreePartsEqualSum(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        total = sum(A)
        if total % 3 != 0:
            return False
        parts, curr = 0, 0
        for x in A:
            curr += x
            if curr == total//3:
                parts += 1
                curr = 0
        return parts >= 3

[2]:
s = Solution1()
A = [0,2,1,-6,6,-7,9,1,2,0,1]
assert s.canThreePartsEqualSum(A) == True
A = [0,2,1,-6,6,7,9,-1,2,0,1]
assert s.canThreePartsEqualSum(A) == False
A = [3,3,6,5,-2,2,5,1,-9,4]
assert s.canThreePartsEqualSum(A) == True